package com.leyou.user.service;

import com.leyou.user.mapper.UserDetailMapper;
import com.leyou.user.pojo.UserDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserDetailService {

    @Autowired
    private UserDetailMapper userDetailMapper;

    /**
     * 根据userId查询用户的收件人信息
     * @param userId
     * @return
     */
    public List<UserDetail> queryUserDetails(Long userId) {
        UserDetail userDetail = new UserDetail();
        userDetail.setUserId(userId);
        return this.userDetailMapper.select(userDetail);
    }

    /**
     * 根据userId添加新的收货地址信息
     * @param userDetail
     * @param userId
     */
    public void addUserDetail(UserDetail userDetail, Long userId) {
        UserDetail userInfo = new UserDetail();

        userInfo.setId(UUID.randomUUID().toString().substring(0, 32).replace("-", ""));
        userInfo.setUserId(userId);

        // 处理收货地址
        String cityName = userDetail.getCity();
        if(StringUtils.isNotEmpty(cityName)){
            int p = cityName.lastIndexOf("省") + 1;
            int c = cityName.lastIndexOf("市") + 1;
            int d = cityName.lastIndexOf("区") + 1;
            userInfo.setState(cityName.substring(0, p));
            userInfo.setCity(cityName.substring(p, c));
            userInfo.setDistrict(cityName.substring(c, d));
            userInfo.setAddress(cityName.substring(d, cityName.length()));
        }

        userInfo.setName(userDetail.getName());
        userInfo.setPhone(userDetail.getPhone());
        userInfo.setZipCode(userDetail.getZipCode());
        userInfo.setStatus(false);

        this.userDetailMapper.insertSelective(userInfo);
    }
}
